package com.presto.directo.mvvm.viewmodel

import android.app.Application
import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.presto.directo.event.LoginSuccess
import com.presto.directo.net.getHttpMap
import com.presto.directo.net.sign
import com.presto.directo.utils.*
import org.greenrobot.eventbus.EventBus

class LoginViewModel(application: Application) : BaseViewModel(application) {

    val smsLiveData = MutableLiveData<String>()

    fun getSmsCode(phone: String) {
        start(onNext = {
            showProgress()
            val map = getHttpMap()
            map["phone"] = phone
            map["type"] = 1
            getApiService().sendSms(map.sign(4)).getResult()
            smsLiveData.value = phone
        }, onComplete = {
            dismissProgress()
        })
    }

    fun login(phone: String, sms: String, context: Context) {
        start(onNext = {
            showProgress()
            val map = getHttpMap()
            map["phone"] = "52$phone"
            map["vcode"] = sms
            val userEntity = getApiService().register(map.sign(6)).getResult()
            if (userEntity.register == "2") {
                Af.sms_login_auto.track(context)
            } else {
                Af.sms_login_auto_return.track(context)
            }
            userEntity.phone = phone
            SPUtil.putObject(UserUtil.USER, userEntity)
            EventBus.getDefault().post(LoginSuccess())
            finish()
        }, onComplete = {
            dismissProgress()
        })
    }

}

const val phonePrefix = "+52"